var REPORT_PATH_PREFIX = "";
var TODO_PATH = "";
function setPathPrefix(path){
	REPORT_PATH_PREFIX =  path;
}
function setPathPreTodo(path){
	TODO_PATH = path;
}
$(function() {
	//把访问路径传到js
	setPathPrefix(reportPath);
	setPathPreTodo(todoPath);
	WASP_WIDGET.initializeSelectStyle();
	WASP_WIDGET.triggerDateRangeStyle("q-uploadTime-range");
	WASP_WIDGET.triggerDateRangeStyle("q-reportTime-range");
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();
    instChange();
	initData();
	//chosenStyle();
	initChoose("todoStatus");
	clears();
});

function initChoose(att){//是否选中(样式切换)
    $('.'+att).on('click', function () {
    	var attr = $(this).attr("class");
    	if(attr.indexOf("fa-square") > -1){
    		$(this).removeClass('fa-square');
    		$(this).addClass('fa-check-square');
		}else{
			$(this).removeClass('fa-check-square');
    		$(this).addClass('fa-square');
		}
	});
}

function clears(){
	$("#resetBtn").click(function(){
		$(".todoStatus").each(function(){
			var attr = $(this).attr("class");
	    	if(attr.indexOf("fa-check-square") > -1){
	    		$(this).removeClass('fa-check-square');
	    		$(this).addClass('fa-square');
			}
		});
		initReportType();
	});
}

//连接跳转过来也要选中样式
function chosenStyle(){
	var jgbg = window.parent.document.getElementById("jgbg");
	window.parent.pageApp.changeLocation($(jgbg));
}
//监管机构与监管报告类型联动
function instChange(){
	$("#instId").on("change",function(){
		initReportType();
	});
}

function initReportType(){
	var _placeholder = $('#reportType').attr("placeholder");
	if (_placeholder == null || _placeholder == '' || _placeholder == 'undefind') {
		_placeholder = "报告类型";
	}
	$('#reportType').select2({
		language:"zh-CN",
		placeholder : _placeholder,
		multiple : false,
		ajax : {
			url : REPORT_PATH_PREFIX + "/getReportTypesByInst.do?instId="+$("#instId").val(),
			type : "GET",
			delay : 400,
			data : function(params) {
				var query;
				if (params.term == null || params.term == '' || params.term == 'undefind') {
					query = {
							reportName : ""
					};
				} else {
					query = {
							reportName : params.term
					};
				}
				return query;
			},
			dataType : "json",
			processResults : function(data) {
				var results = $.map(data, function(obj) {
					return {
						id : obj.REPORT_ID,
						text : obj.REPORT_NAME
					};
				});
				return {
					results : results
				};
			}
		},
		cache : false,
		templateSelection : function(obj) {
			return $('<span data-html="true" >' + obj.text + '</span>').tooltip();
		}
	});
}

var $regulatoryReportList = $("#regulatoryReportList");

function initData(){

	$regulatoryReportList.jqGrid({
        url: REPORT_PATH_PREFIX+'/regulatoryReportListPageNew.do',
        caption: '',
        datatype: "local",
        colNames:["reportId","status","报告类型", "监管机构", "报告日期", "状态","材料上传日期","报告上传日期","noFile","操作"],        
		colModel:[
		          	{name:'reportId',index:'reportId',align:'left',key:true, hidden:true, resizable:true,sortable:false},
		          	{name:'status',index:'status',align:'left', hidden:true, resizable:true,sortable:false},
		          	{name:'reportTypeName',index:'reportTypeName',align:'left', hidden:false, resizable:true,sortable:false},
					{name:'instSName',index:'instSName',align:'left', hidden:false, sortable:false },
					{name:'reportDate',index:'reportDate',align:'left', hidden:false, resizable:true,sortable:false},
					{name:'statusNm',index:'statusNm',align:'left',hidden:false, resizable:true,sortable:false},
					{name:'uploadTime',index:'uploadTime',align:'left', hidden:false, resizable:true,sortable:false},
					{name:'endTime',index:'endTime',align:'left',hidden:false, resizable:true,sortable:false},
					{name:'noFile',index:'noFile',align:'left',hidden:true, resizable:true,sortable:false},
					{name:'option',index:'option', width: 400, resizable:true, align:'left', sortable:false}
				],  
        rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        postData:{},
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },
        multiselect: true,
        pager: "#regulatoryReportPage",
        hidegrid: false,
        gridComplete: function(){
        	var ids = $regulatoryReportList.jqGrid('getDataIDs');
	        	for(var i=0;i < ids.length;i++){
	        	var rowId = ids[i];
	        	var rowdata=$regulatoryReportList.jqGrid('getRowData',rowId);
				var params = {'mdown' : 'regulatoryMaterialDwnTemp','rupload' : 'regulatoryReportUploadTemp','rdown' : 'regulatoryReportDownloadTemp'};
				var permissionButton = Permission_Button.configPermissionButton(params);
				var status = rowdata["status"];
				var noFile = rowdata["noFile"];
				if(noFile!='Y'){
					if(status == 'S' || status == 'C' || status == 'E'){
						permissionButton.mdown = Permission_Button.clickPermissionButton('regulatoryMaterialDwnTemp',"downNew('" + rowId +"','M')");
					}
				}
				if(status == 'C' ){
					permissionButton.rupload = Permission_Button.clickPermissionButton('regulatoryReportUploadTemp',"regulatoryReportAdd('"+rowId+"','R')");
				}
				if(status=="E"){
					permissionButton.rdown = Permission_Button.clickPermissionButton('regulatoryReportDownloadTemp',"downNew('" + rowId +"','R')");
				}
				$regulatoryReportList.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
        	}
        }
	});

	$regulatoryReportList.navGrid('#regulatoryReportPage', {
		edit : false,
		add : false,
		del : false,
		search : false,
		refreshstate: 'current' 
	});

	$regulatoryReportList.jqGrid('setFrozenColumns');
	jqGridResize($regulatoryReportList);
	$regulatoryReportList.jqGrid('setGridParam',{datatype:'json'});//初始的时候不查询
	json?queryByParamater(json):queryByCondtion(true);//判断是否来自首页
}

function getStatus(){
	var todoStatus = "";
	$(".todoStatus").each(function(){
		if($(this).attr("class").indexOf("fa-check-square") > -1){
			todoStatus += $(this).attr("value") + ",";
		}
	});
	return todoStatus;
}

function queryByParamater(json){
	var obj = JSON.parse(json);
	$("#q-reportTime-range").val(obj.reportTimeBeg + " - " + obj.reportTimeEnd);
	var reportType = "";
	$("#instId").val(obj.instId).trigger('change');
	WASP_WIDGET.initializeSelectVal("reportType", obj.reportType, obj.reportTypeName);
	if(obj.finishFlag != null && obj.finishFlag != ''){
		if(obj.finishFlag == '1'){
			$(".todoStatus").each(function(){
				if($(this).attr("value") == 'E'){
					$(this).removeClass('fa-square');
		    		$(this).addClass('fa-check-square');
				}
			});
		}else if(obj.finishFlag == '0'){
			$(".todoStatus").each(function(){
				if($(this).attr("value") != 'E'){
					$(this).removeClass('fa-square');
		    		$(this).addClass('fa-check-square');
				}
			});
		}
		
	}
	var todoStatus = getStatus();
	//var downFlag = obj.finishFlag == '1' ? 'Y' : 'N';
	//$("#downFlag").val(downFlag).trigger('change.select2');
	var postData = $regulatoryReportList.jqGrid("getGridParam", "postData");
	$.extend(postData, {
		'sp[instId]':obj.instId,
		'sp[reportType]' : obj.reportType,
		'sp[todoStatus]' : todoStatus,
        'sp[reprotDateBgn]': $("#q-reportTime-range").getDateRangeValue()[0],
        'sp[reprotDateEnd]': $("#q-reportTime-range").getDateRangeValue()[1]
    });
	$regulatoryReportList.trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
}

function queryByCondtion(flag) {
	var postData = $regulatoryReportList.jqGrid("getGridParam", "postData");
	var instId = $("#instId").val();
	var reportType = $("#reportType").val();
	var uploadFlag = $("#uploadFlag").val();
	var todoStatus = getStatus();
    $.extend(postData, {
        'sp[instId]':instId,
        'sp[reportType]':reportType,
        'sp[todoStatus]' : todoStatus,
        'sp[uploadFlag]':uploadFlag,
        'sp[uploadDateBgn]': $("#q-uploadTime-range").getDateRangeValue()[0],
		'sp[uploadDateEnd]': $("#q-uploadTime-range").getDateRangeValue()[1],
		'sp[reprotDateBgn]': $("#q-reportTime-range").getDateRangeValue()[0],
		'sp[reprotDateEnd]': $("#q-reportTime-range").getDateRangeValue()[1]
    });
    if (flag) {
    	$regulatoryReportList.trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
    } else {
    	$regulatoryReportList.trigger("reloadGrid"); //重新载入Grid表格
    }
};

function regulatoryReportAdd(reportId,flag){
	/*var actionUrl = encodeURI(REPORT_PATH_PREFIX + "/regulatoryReportAddNew.do?sp[reportIds]="+reportId+"&flag="+flag);*/
	var actionUrl = TODO_PATH + "/toEndFileUploadView4Biz.do?bizId="+reportId+"&bizType=INFO_DIS_REGULATORY";
	window.open(actionUrl);
}

function downNew(reprotIds,flag){
	var actionUrl;
	var attachFlag = judgeHasAttachNew([reprotIds],flag);
	if(flag == "M"){
		flagStr = "材料";
		actionUrl = encodeURI(TODO_PATH+"/batchTodoFileDownload4Biz.do?bizType=INFO_DIS_REGULATORY&bizId=" + reprotIds);
	}else if(flag == "R"){
		flagStr = "报告";
		actionUrl = encodeURI(TODO_PATH+"/batchEndFileDownload4Biz.do?bizType=INFO_DIS_REGULATORY&bizId=" + reprotIds);
	}
	if(!attachFlag){
		ctools.alert("选中数据未上传"+flagStr+"!","","warning");
		return;
	}
	
	window.location = actionUrl;
}

function judgeHasAttachNew(ids,flag){
	var attachFlag = false;
	var fileType;
	if(flag == "M"){
		fileType = "input";
	}else if(flag == "R"){
		fileType = "output";
	}
	$.ajax({
		dataType: "json",
		type:'GET',
		url:encodeURI(TODO_PATH+"/validateExistsFile.do?bizType=INFO_DIS_REGULATORY&bizId="+ ids.join(",")+"&fileType="+fileType),
		async:false,
		success: function(data){
			attachFlag = data.success;
		},
	});
	return attachFlag;
}


function batchDownNew(flag){
	var ids = $regulatoryReportList.jqGrid('getGridParam', 'selarrrow');//选择多选
	if(ids.length == 0){
		ctools.alert('请至少选择一条数据!',"","warning");
		return;
	}
	var actionUrl;
	var attachFlag = judgeHasAttachNew(ids,flag);
	var flagStr ;
	if(flag == "M"){
		flagStr = "材料";
		actionUrl = encodeURI(TODO_PATH+"/batchTodoFileDownload4Biz.do?bizType=INFO_DIS_REGULATORY&bizId=" + ids.join(","));
	}else if(flag == "R"){
		flagStr = "报告";
		actionUrl = encodeURI(TODO_PATH+"/batchEndFileDownload4Biz.do?bizType=INFO_DIS_REGULATORY&bizId=" + ids.join(","));
	}
	
	if(!attachFlag){
		ctools.alert("选中数据未上传"+flagStr+"!","","warning");
		return;
	}
	window.location = actionUrl;
}
/*******************属于列表的操作未关联我的（已废弃）*********************/
function judgeHasAttach(ids,flag){
	var attachFlag = false;
	$.ajax({
		dataType: "json",
		type:'GET',
		url:encodeURI(REPORT_PATH_PREFIX+"/judgeHasAttach.do?sp[reportIds]="+ ids.join(",")+"&sp[flag]="+flag+"&sp[batch]=true"),
		async:false,
		success: function(data){
			attachFlag = data;
		},
	});
	return attachFlag;
}


function batchDown(flag){
	var ids = $regulatoryReportList.jqGrid('getGridParam', 'selarrrow');//选择多选
	if(ids.length == 0){
		ctools.alert('请至少选择一项!',"","warning");
		return;
	}
	var flagStr ;
	if(flag == "M"){
		flagStr = "材料";
	}
	if(flag == "R"){
		flagStr = "报告";
	}
	var attachFlag = judgeHasAttach(ids,flag);
	if(attachFlag){
		ctools.alert("选中数据未上传"+flagStr+"!","","warning");
		return;
	}
	var actionUrl = encodeURI(REPORT_PATH_PREFIX+"/regulatoryReportDownNew.do?sp[reportIds]="+ ids.join(",")+"&sp[flag]="+flag+"&sp[batch]=true");
    window.location = actionUrl;  
}

function down(rowid,instSName,reportTypeName,reportDate,flag){
	if(!instSName){
		instSName = "-";
	}
	if(!reportTypeName){
		reportTypeName = "-";
	}
	if(!reportDate){
		reportDate = "-";
	}
	var actionUrl = encodeURI(REPORT_PATH_PREFIX+"/regulatoryReportDownNew.do?sp[reportIds]="+ rowid+"&sp[instSName]="
			+instSName+"&sp[reportTypeName]="+reportTypeName+"&sp[reportDate]="+reportDate+"&sp[flag]="+flag+"&sp[batch]=false");
    window.location = actionUrl;  
}